package com.bw.permission.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.bw.permission.common.AjaxResult;
import com.bw.permission.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("product")
public class ProductController {


    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @return
     */
    @PostMapping("save")
    @Transactional
    public AjaxResult save(@RequestBody Product product) throws InterruptedException {
        //验证表单是否重复提交
        String formData = JSON.toJSONString(product);
        String md5 = SecureUtil.md5(formData);//签名
        //redis setnx 命令，加锁操作
        Boolean result = redisTemplate.opsForValue().setIfAbsent(md5, null,60,TimeUnit.SECONDS);
        if (!result) {
            return AjaxResult.err(400, "表单重复提提交了");
        }
        //测试表单重复提交效果
        Thread.sleep(2000);


        //保持数据库

        //给kafka发送消息，异步保存Es索引库
        product.setMsgId(UUID.randomUUID().toString()); //消息唯一Id
        kafkaTemplate.send("productTopic", JSON.toJSONString(product));
        log.info("kafka 消息发送成功：{}",product.getName());
        return AjaxResult.ok();
    }
}
